Fork me on GitHub

3. Longest Substring Without Repeating Characters

JAVA刷题ing

Medium

Given a string, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
  1. two point
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> mem = new HashSet<Character>();
int i = 0; int j = 0;
int n = s.length();
int ans = 0;
while(i < n && j < n){
if(!mem.contains(s.charAt(j))){

mem.add(s.charAt(j++)); // after finishing this, j += 1
ans = Math.max(ans, j-i);
// this why not j-i+1, because at this time j already plus 1
// System.out.println("here"+mem+s.charAt(j-1));
}else{
// we move i until find the same element
mem.remove(s.charAt(i++));
// System.out.println("d"+mem+s.charAt(j));
}
}
return ans;
}
}

Syntax:

1
2
3
Set<Character> mem = new HashSet<Character>(); // correct
HashSet<Character> mem = new HashSet<Charater>(); // correct
Set<Character> mem = new Set<Character>(); // wrong Set is abstract; cannot be instantiated
  1. 关于Hashmap的声明,为什么前面可以是Set后面必须是HashSet,这里。总之,Set包括(HashSet, LinkedHashSet or TreeSet)前面是对对象类型的声明,类型可以是总的,或者是具体的,但后面是调用接口,对对象初始化,这里就没有set这一选项了。
1
System.out.println("d"+mem+s.charAt(j));
  1. debug必备。print don’t change the line, but println (means print line next) change line after printing. using ‘+’ to link two string. ‘ ‘ can only be used to one char, “ “ can be used to string.
Shuolin Tian wechat
欢迎加我微信交流